package com.zhugang.week12;

import java.util.Arrays;

/**
 * @program algorithms
 * @description: smallestDifference
 * @author: chanzhugang
 * @create: 2022/09/07 11:58
 */
public class SmallestDifference {

    /**
     * 面试题 16.06 最小差
     * 类似合并两个有序数组：双指针
     *
     * @param a
     * @param b
     * @return
     */
    public int smallestDifference(int[] a, int[] b) {
        // 双指针：i、j分别指向两个数组
        Arrays.sort(a);
        Arrays.sort(b);

        int m = a.length;
        int n = b.length;
        int i = 0;
        int j = 0;
        long min = Long.MAX_VALUE;
        while (i < m && j < n) {
            if (a[i] >= b[j]) {
                min = Math.min(min, (long) a[i] - b[j]);
                j++;
            } else {
                min = Math.min(min, (long) b[j] - a[i]);
                i++;
            }
        }
        return (int) min;
    }
}